package service

import (
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/gjson"
	"duoke/utils/gstr"
	"duoke/utils/orm"
	"reflect"
)

var SystemSetting = new(SystemSettingService)

type SystemSettingService struct{}

func (s *SystemSettingService) Save(req map[string]interface{}) error {
	setting := new(tables.Setting)
	has, err := orm.Db.Get(setting)
	if err != nil {
		return err
	}
	var affected int64
	// 反射设置结构体值
	rve := reflect.ValueOf(setting).Elem()
	rve.FieldByName(gstr.CamelString(gconv.String(req["field"]))).SetString(gjson.StructOrMap2Json(req["data"]))
	if has {
		affected, err = orm.Db.ID(setting.Id).Cols(gconv.String(req["field"])).Update(setting)
	} else {
		affected, err = orm.Db.Insert(setting)
	}
	if affected == 0 {
		return nil
	}
	return err
}
func (s *SystemSettingService) Info(field string) (map[string]interface{}, error) {
	setting := new(tables.Setting)
	has, err := orm.Db.Get(setting)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	rve := reflect.ValueOf(*setting)
	var data map[string]interface{}
	gjson.Json2StructOrMap(rve.FieldByName(gstr.CamelString(field)).String(), &data)
	return data, nil
}
